<template>
  <fixed-pagination>
    <div :class="{'mobile-btn-list':showMobilePage}" class="center">
      <!-- 待提交 -->
      <template v-if="projectStatus === 0">
        <el-button v-if="hasRouteAuth('crm:project:submitFirstTrial') || isAdmin" type="primary" size="small" class="submit-btn" @click="submitExamine">提交审批</el-button>
        <el-button v-if="editAuth" type="primary" size="small" class="cancel-btn-style" @click="toEdit">编辑项目</el-button>
      </template>
      <!-- 待初审 -->
      <template v-if="projectStatus === 1">
        <el-button v-if="backSubmitAuth" type="danger" plain size="small" class="submit-btn" @click="projectBack(0)">退回</el-button>
        <el-button v-if="hasRouteAuth('crm:project:firstTrial') || isAdmin" type="primary" size="small" class="submit-btn" @click="firstExamine(1)">通过</el-button>
        <el-button v-if="editAuth" type="primary" size="small" class="cancel-btn-style" @click="toEdit">编辑项目</el-button>
      </template>
      <!-- 待复审 -->
      <template v-if="projectStatus === 2">
        <el-button v-if="backFirstAuth" type="danger" plain size="small" class="submit-btn" @click="projectBack(1)">退回</el-button>
        <el-button v-if="hasRouteAuth('crm:project:recheck') || isAdmin" type="primary" size="small" class="submit-btn" @click="recheckExamine(1)">通过</el-button>
      </template>
      <!-- 待确认 -->
      <template v-if="projectStatus === 3">
        <el-button v-if="backRecheckAuth" type="danger" plain size="small" class="submit-btn" @click="projectBack(2)">退回</el-button>
        <el-button v-if="hasRouteAuth('crm:project:confirm') || isAdmin" type="primary" size="small" class="submit-btn" @click="confirm(1)">通过</el-button>
      </template>
      <!-- 待封存 -->
      <template v-if="projectStatus === 4">
        <el-button v-if="backConfirmAuth" type="danger" plain size="small" class="submit-btn" @click="projectBack(3)">退回</el-button>
        <el-button v-if="hasRouteAuth('crm:project:seal') || isAdmin" type="primary" size="small" class="submit-btn" @click="projectSeal">封存</el-button>
        <!-- <el-button type="primary" size="small" class="empty-btn-style">导出Excel</el-button> -->
      </template>
      <!-- 已封存 -->
      <template v-if="projectStatus === 5">
        <el-button v-if="backSealAuth" type="danger" plain size="small" class="submit-btn" @click="cancelSeal">取消封存</el-button>
      </template>
      <export-button
        v-if="hasRouteAuth('crm:project:export') || isAdmin"
        :export-api="'admin/project/detail/export'"
        :export-name="detailData.projectName || '项目'"
        :query-data="{id: projectId}"
        :default-loading="false"
        style="margin-left:10px;"
        @onSuccessExport="onSuccessExport"
      >
        导出Excel
      </export-button>
      <el-button
        v-if="!showMobilePage"
        type="info"
        size="small"
        style="margin-left:10px;"
        class="cancel-btn-style"
        @click="toBack">返回</el-button>
    </div>
    <projectOpeator ref="projectOpeator" @cancelSealCallBack="cancelSealCallBack" @getInfo="getInfo"/>
  </fixed-pagination>
</template>

<script>
import { mapState } from 'vuex';
import ElMessage from '@/utils/message';
import { hasRouteAuth } from '@/utils/permission';
// components
import projectOpeator from './model/projectOpeator';
import ExportButton from '@/components/Customer/detail/exportBtn';

export default {
  components: { projectOpeator, ExportButton },
  props: {
    projectId: {
      type: Number | String,
      default: ''
    },
    detailData: {
      type: Object,
      default: () => {
        return {};
      }
    }
  },
  data() {
    return {
      clientWidth: ''
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo,
      'showMobilePage': state => state.app.showMobilePage
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员';
    },
    backSubmitAuth() { // 待初审 -> 待提交, 拥有初审权限 或者 提交审批权限
      return hasRouteAuth('crm:project:firstTrial') || hasRouteAuth('crm:project:submitFirstTrial') || this.isAdmin;
    },
    backFirstAuth() { // 待复审 -> 待初审, 拥有复审权限 或者 初审权限
      return hasRouteAuth('crm:project:recheck') || hasRouteAuth('crm:project:firstTrial') || this.isAdmin;
    },
    backRecheckAuth() { // 待确认 -> 待复审, 拥有确认权限 或者 复审权限
      return hasRouteAuth('crm:project:confirm') || hasRouteAuth('crm:project:recheck') || this.isAdmin;
    },
    backConfirmAuth() { // 待封存 -> 待确认 或者（待封存 -> 待复审）
      const isMedim = this.detailData.departmentName ? this.detailData.departmentName.indexOf('销售部') !== -1 : false;
      const isConfirmAuth = !isMedim ? hasRouteAuth('crm:project:confirm') : hasRouteAuth('crm:project:recheck');
      return hasRouteAuth('crm:project:seal') || isConfirmAuth || this.isAdmin;
    },
    backSealAuth() { // 已封存 -> 待封存
      return hasRouteAuth('crm:project:cancelSeal') || this.isAdmin;
    },
    projectStatus() {
      // 待提交:0    待初审: 1   待复审: 2   待确认: 3   待封存: 4  已封存: 5
      return this.detailData.projectStatus || 0;
    },
    editAuth() { // 设置编辑权限判断
      const cooperationName = this.detailData.cooperation ? this.detailData.cooperation.map(i => i.userName).join(',') : '';
      if (this.projectStatus === 0 || this.projectStatus === 1) {
        if (this.isAdmin) {
          return true;
        } else if (hasRouteAuth('crm:project:editAdmin')) {
          return true;
        } else if (hasRouteAuth('crm:project:edit') && (this.detailData.creator === this.userInfo.userName || this.detailData.projectDirectorId === this.userInfo.id || cooperationName.indexOf(this.userInfo.userName) >= 0)) {
          return true;
        } else {
          return false;
        }
      } else {
        return false;
      }
    }
  },
  created() {
    // this.getAllDeptList();
  },
  methods: {
    hasRouteAuth,
    // 待提交-提交初审
    submitExamine() {
      const extendParams = { ids: this.projectId };
      // 如果是通过，默认填充上次选择的人员
      let defaultObjectUser = null;
      if (localStorage.getItem('submitExamineHttp') !== 'undefined') {
        defaultObjectUser = JSON.parse(localStorage.getItem('submitExamineHttp'));
      }
      this.$refs.projectOpeator.submitExamine({ extendParams, defaultObjectUser, projectId: this.projectId });
    },
    // 待初审-通过/退回 status:1 通过 0:退回
    firstExamine(status = 1) {
      const extendParams = { ids: this.projectId, status };
      const params = {
        extendParams,
        defaultObjectUser: [],
        projectId: this.projectId
      };
      // 如果是退回，则回填创建人
      if (status === 0 && this.detailData.creator && this.detailData.creatorId) {
        params.defaultObjectUser = [{ id: this.detailData.creatorId, userName: this.detailData.creator }];
      }
      // 如果是通过，默认填充上次选择的人员
      if (status && localStorage.getItem('firstExamineUsers') !== 'undefined') {
        params.defaultObjectUser = JSON.parse(localStorage.getItem('firstExamineUsers'));
      }
      this.$refs.projectOpeator.firstExamine(params);
    },
    // 待复审-通过/退回
    recheckExamine(status = 1) {
      const extendParams = { ids: this.projectId, status };
      const isMediumSale = this.detailData.departmentName ? this.detailData.departmentName.indexOf('销售部') >= 0 : false;
      const params = {
        extendParams,
        defaultObjectUser: [],
        projectId: this.projectId,
        isMediumSale
      };
      // 如果是退回或者销售部，则回填上一步的审批人员
      if ((status === 0 || isMediumSale) && this.detailData.opeatorUser && this.detailData.opeatorUserId) {
        params.defaultObjectUser = [{ id: this.detailData.opeatorUserId, userName: this.detailData.opeatorUser }];
      }
      // 如果是通过，默认填充上次选择的人员
      if (status && localStorage.getItem('recheckExamineHttp') !== 'undefined') {
        params.defaultObjectUser = JSON.parse(localStorage.getItem('recheckExamineHttp'));
      }
      this.$refs.projectOpeator.recheckExamine(params);
    },
    // 待确认
    confirm(status = 1) {
      const extendParams = { ids: this.projectId, status };
      const params = {
        extendParams,
        defaultObjectUser: [],
        projectId: this.projectId
      };
      // 回填上一步的审批人员
      if (this.detailData.opeatorUser && this.detailData.opeatorUserId) {
        params.defaultObjectUser = [{ id: this.detailData.opeatorUserId, userName: this.detailData.opeatorUser }];
      }
      // 如果是通过，默认填充上次选择的人员
      if (status && localStorage.getItem('confirmHttp') !== 'undefined') {
        params.defaultObjectUser = JSON.parse(localStorage.getItem('confirmHttp'));
      }
      this.$refs.projectOpeator.confirm(params);
    },
    // 退回
    projectBack(state) {
      // 销售部没有待确认（3） 这一步
      if (state === 3 && this.detailData.departmentName) {
        state = this.detailData.departmentName.indexOf('销售部') !== -1 ? 2 : 3;
      }
      const extendParams = { ids: this.projectId, status: state, currentStatus: this.projectStatus };
      const params = {
        extendParams,
        defaultObjectUser: [],
        projectId: this.projectId
      };
      // 退回到待发布时，回填创建人
      if (state === 0 && this.detailData.creatorId && this.detailData.creator) {
        params.defaultObjectUser = [{ id: this.detailData.creatorId, userName: this.detailData.creator }];
      } else if (this.detailData.opeatorUser && this.detailData.opeatorUserId) {
      // 回填上一步的审批人员
        params.defaultObjectUser = [{ id: this.detailData.opeatorUserId, userName: this.detailData.opeatorUser }];
      }
      this.$refs.projectOpeator.projectBack(params);
    },
    // 封存
    projectSeal() {
      if (!this.detailData.attachment || this.detailData.attachment.length === 0) {
        ElMessage.error('请上传附件后再进行封存');
        return;
      }
      const params = {
        ids: this.projectId
      };
      this.$refs.projectOpeator.projectSeal(params);
    },
    cancelSealCallBack() {
      this.$emit('fetchDataChargeList');
    },
    cancelSeal() {
      const params = {
        ids: this.projectId
      };
      this.$refs.projectOpeator.cancelSeal(params);
    },
    getInfo() {
      this.$emit('getDetail');
      this.$emit('freshData');
    },
    // tool
    toBack() {
      this.$router.push({
        name: 'projectList'
      });
    },
    onSuccessExport() {
      this.$emit('getOperateReports');
    },
    toEdit() {
      this.$router.push({
        name: 'editProject',
        params: { id: this.projectId }
      });
    }
  }
};
</script>

<style lang="scss" scoped>
.empty-btn-style {
  border-color: #406EFF;
  background: #fff;
  color: #406EFF;
  &:hover {
    background: #406EFF;
    color: #fff;
  }
}
.mobile-btn-list {
  &::v-deep {
    .el-button {
      padding: 7px 11px;
    }
  }
}
</style>
